import Vue from "vue"
import VueRouter from "vue-router"

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/frontHome'
    },
    {
        path: '/login',
        name: 'Login',
        component: ()=>import('../views/Login.vue')
    },
    {
        path: '/regist',
        name: 'Regist',
        component: ()=>import('../views/Regist.vue')
    },

    {
        path: '/backHome',
        name: 'BackHome',
        component: () => import('../views/back/BackHome.vue'),
        children: [
            {
                path: '',
                name: 'Index',
                component: () => import('../views/back/Index.vue')
            },
            {
                path: 'userMange',
                name: 'UserManage',
                component: () => import('../views/back/UserManage.vue')
            },{
                path: 'userInfo',
                name: 'UserInfo',
                component: () => import('../views/back/UserInfo.vue'),
                children: [
                    {
                        path: '',
                        name: 'UserProfile',
                        component: () => import('../views/back/UserProfile.vue')
                    },
                    {
                        path: 'userPwd',
                        name: 'UserPwd',
                        component: () => import('../views/back/UserPwd.vue')
                    }
                ]

            },
            {
                path: 'goodsMange',
                name: 'GoodsMange',
                component: () => import('../views/back/GoodsMange.vue')
            }
        ]
    },
    {
        path: '/frontHome',
        name: 'FrontHome',
        component: () => import('../views/front/FrontHome.vue'),
        // children: [
        //     {
        //         path: '',
        //         name: 'Index',
        //         component: () => import('../views/back/Index.vue')
        //     },
        // ]
    }
]

const router = new VueRouter({
    mode: 'history',
    routes
})

// 添加请求拦截器
router.beforeEach((to, from, next) => {
    if(to.name == "Regist" || to.name == "Login" || to.name == "FrontHome"){
        // 以上请求放行
       next();
       return;
    }
    // 获取浏览器的用户信息
    const userAuth=localStorage.getItem("userAuth");
    if(userAuth == 2){
        // root用户随便访问
        next();
        return;
    }else{
        // 否则跳转登录页面
        next("Login");
        alert("用户权限不够无法访问,请输入对应的账号访问");
        return;
    }
    // 否则跳转登录页面
    next("Login");
})




// 解决 vue-router 升级导致的 Uncaught(in promise)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}
export default router